/**
 * Created by yang.fan on 2017/11/17.
 */
import React from 'react';
import {Modal, Button,Row,Col,Cascader,Input,Form,message} from 'antd';
import styles  from './Track.less';
import { request } from '../../config/request'
const { Component } = React
import { cloneDeep } from 'lodash';
// 引入全局配置
import config from '../../config/config'
// 异步静态资源
import LoadAssets from 'load-assets'
import {QueryCondition} from 'widget/Grid/Grid'
import AdvanceSearch from '../CollapsiblePanels/AdvanceSearch'
import $ from 'jquery'
/*
 *
 * 地图组件
 *
 */
const FormItem = Form.Item;
const {Search} = Input
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 19 },
};


export default class Track extends Component {
  // 构造函数
  constructor(props, context) {
    super(props, context);
    this.state = {
      queryList: cloneDeep(props.queryList),
      //根据经纬度获取逆地理位置
      address: '',

      //按钮的显示隐藏
      btnDiv: this.props.btnDiv || true,

      //开启关闭按钮
      visible: this.props.visible || false,

      //确定按钮
      cbk: ()=>{
        this.props.cbk(this.state.latAndLon, this.state.address);
      },

      //取消
      cancal: ()=>{
        this.props.cancal&&this.props.cancal()
      },

      // 地图实例
      map: null,

      // 图标实例
      marker: null,

      //经纬度 默认显示北京首都的经纬度
      latAndLon: this.props.latAndLon || [113.437218, 23.103965],

      //是否开启地图的点击功能
      clickRes: this.props.clickRes || true,
      //省市配置
      options:this.props.options,
      //选择的地址
      selectAddress:''
    }

  }

  // 加载静态资源及地图
  loadAssetsAndMap(key){
    let THIS = this
    // 加载地图所需静态资源
    let assetsArray = [
      'https://cache.amap.com/lbs/static/main1119.css',
      'https://cache.amap.com/lbs/static/es5.min.js',
      'https://webapi.amap.com/maps?v=1.4.10&key=' +'7e61745f0e479ccedbcc70071ec3f690'
    ]
    // 加载静态资源
    new LoadAssets(assetsArray, function(){
      // DOM加载完成之后，再加载地图
      if(THIS.props.latAndLon.length == 0||!THIS.props.latAndLon[0]){
        THIS.initMapfrist()
      }else{
        THIS.initMap()
      }
      
    })
  }

  //弹窗的确定按钮
  handleOk(){
    //console.log('确定')
  }

  //弹窗的取消按钮
  handleCancel(){
    let THIS = this;
    this.setState({visible: false}, ()=>{
      THIS.state.cancal();
    });
  }

  initMapfrist(){
    let self = this
    var map = new AMap.Map(self.refs.container, {
      resizeEnable: true
    });
    map.plugin('AMap.Geolocation', function() {
      var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,//是否使用高精度定位，默认:true
          timeout: 5000,          //超过10秒后停止定位，默认：5s
          buttonPosition:'RB',    //定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
          GeoLocationFirst:true,
      });
      map.addControl(geolocation);
      geolocation.getCurrentPosition(function(status,result){
          if(status=='complete'){
              self.setState({
                latAndLon:[result.position.lng, result.position.lat]
              },()=>{
                self.initMap()
              })
          }else{
            geolocation.getCityInfo(function(status,result){
              self.setState({
                latAndLon:result.center
              },()=>{
                self.initMap()
              })
            })
            console.log(result)
          }
      });
  });
  }
   
  // 加载地图实例
  initMap(){
    let THIS = this
    // 创建地图实例
    let map = new AMap.Map(THIS.refs.container, {
      resizeEnable: true,
      zoom:13,//地图显示的缩放级别
      center: THIS.state.latAndLon,//地图中心点
    });
    // 添加缩放地图工具
    if(map){
      map.plugin(["AMap.ToolBar"], function() {
        map.addControl(new AMap.ToolBar());
      });
      if(location.href.indexOf('&guide=1')!==-1){
        map.setStatus({scrollWheel:false})
      }
    }

    //设定图标位置
    var marker = new AMap.Marker({
      position: THIS.state.latAndLon,
      draggable: false,
      cursor: 'move',
    });

    // 设置点标记的动画效果，此处为弹跳效果
    marker.setAnimation('AMAP_ANIMATION_BOUNCE');
    marker.setMap(map);
    
    //获取逆地理位置
    THIS.getAddress(THIS.state.latAndLon[0], THIS.state.latAndLon[1]);

    if(this.state.btnDiv){
      //点击地图
      map.on('click', function(e) {
        //首先清除原有的图标
        THIS.state.marker.setMap(null);

        // alert('您在[ '+e.lnglat.getLng()+','+e.lnglat.getLat()+' ]的位置点击了地图！');
        let lLArr = [e.lnglat.getLng(),e.lnglat.getLat() ];
        //获取逆地理位置
        THIS.getAddress(e.lnglat.getLng(),e.lnglat.getLat());

        THIS.setState({latAndLon: lLArr}, ()=>{
          //重新设定图标位置
          THIS.movePos();

        });
      });
    }

    // 放到状态机
    this.setState({map, marker})

  }

  //定位点移动事件
  movePos(){
    let THIS = this;
    let map = this.state.map;

    var marker = new AMap.Marker({
      position: THIS.state.latAndLon,
      draggable: false,
      cursor: 'move',
    });

    // 设置点标记的动画效果，此处为弹跳效果
    marker.setAnimation('AMAP_ANIMATION_BOUNCE');
    marker.setMap(map);

    //更新定位图标
    this.setState({marker})
  }
  
  //逆地理编码
  getAddress(lng, lat){
    //搜索条件
    var self =this
    let obj = {
      location: lng + ',' + lat,
      key: config.mapCfg.webServkey,
    };
    $.ajax({
      type: 'GET',
      url: 'https://restapi.amap.com/v3/geocode/regeo',
      data:obj,
      contentType:'application/x-www-form-urlencoded; charset=UTF-8',
      success: function (data) {
          //console.log(data.regeocode.formatted_address)
          //赋值地址
          let result =  data.regeocode&&data.regeocode.formatted_address;
          // 放到状态机
          self.setState({address: result})
      },
      error: function (xhr, type) {
        alert('出错了, 请重试')
      }
    })
  }
  //ip定位
  // getIp(cbk){
  //   //搜索条件
  //   var self =this
  //   let obj = {
  //     key: config.mapCfg.webServkey,
  //     ip:""
  //   };
  //   $.ajax({
  //     type: 'GET',
  //     url: 'https://restapi.amap.com/v3/ip',
  //     data:obj,
  //     contentType:'application/x-www-form-urlencoded; charset=UTF-8',
  //     success: function (data) {
  //        //console.log(data.city+data.province)
  //        let arr = data.rectangle.split(';')
  //        console.log(arr[0])
  //        let obj = arr[1].split(',')
  //        let  latAndLon = [obj[0],obj[1]]
  //        self.setState({
  //         latAndLon
  //       },()=>{
  //         console.log(cbk)
  //         cbk&&cbk(config.mapCfg.webServkey)
  //       })
  //     },
  //     error: function (xhr, type) {
  //       alert('出错了, 请重试')
  //     }
  //   })
  // }
  //地理编码
  getLatAddress(address){
    var self =this
    let obj = { 
      address,
      key: config.mapCfg.webServkey,
    };
    $.ajax({
      type: 'GET',
      url: 'https://restapi.amap.com/v3/geocode/geo',
      data:obj,
      contentType:'application/x-www-form-urlencoded; charset=UTF-8',
      success: function (data) {
          //console.log(data)
          //赋值地址
          if(data.info == "OK"){
            let result =  data.geocodes[0].location.split(',')
            // 放到状态机
            self.setState({latAndLon:result},()=>{
              self.initMap()
            })
          }else{
            message.error('根据地址查询位置失败');
          }
          
      },
      error: function (xhr, type) {
        alert('出错了, 请重试')
      }
    })
  }
  //弹窗的重置按钮
  handleReset() {
    this.clearSearch(this.getProductList)
  }
  //弹窗的查询按钮
  handleSearch() {
    this.setState({
      pageNum: 1,
      pageSize: 10
    }, () => {
      this.getProductList()
    })
  }
  onChange(value,item) {
    let address = ''
    for(var i=0; i<item.length;i++){
      address+=item[i].label
    }
    this.setState({
      selectAddress:address
    })
    console.log(address)
    this.getLatAddress(address)
  }
  render() {
    let THIS = this;
    let {selectAddress,latAndLon} =this.state;
    return (
      <div className={styles.map}>
        <Modal
          visible={THIS.state.visible}
          title={'地图'}
          onOk={this.handleOk}
          onCancel={this.handleCancel.bind(THIS)}
          width={1000}
          footer={null}
        >
          <div className="public_listMain">
            <Row>
              <Col span={7}>
                <FormItem {...formItemLayout}
                label="省市">
                <Cascader placeholder="请选择" options={THIS.state.options} onChange={this.onChange.bind(this)} />
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem {...formItemLayout}>
                <Search
                  placeholder="请输入地址"
                  onSearch={(value) => {
                    if(selectAddress.length>0){
                      let address = selectAddress + value
                      return this.getLatAddress(address)
                    }else{
                      return this.getLatAddress(value)
                    }
                    
                  }}
                  enterButton
                />
                </FormItem>
              </Col>
              <Col span={5}>
                <span>
                规则遵循：国家、省份、城市、区县、城镇、乡村、街道、门牌号码、屋邨、大厦，如：北京市朝阳区阜通东大街6号。
                </span>
              </Col>
            </Row>
          </div>
          <div className={styles.mapExp}>请在地图中点击定位点至您的门店所在位置，并点击“确认”完成设置。</div>
          <div className={styles.mapCoo}>
            <span>你当前选取的位置为：</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            {THIS.state.address}&nbsp;&nbsp;&nbsp;
            ( 经度：{latAndLon[0]?latAndLon[0]:0}&nbsp;&nbsp;&nbsp;
            纬度：{latAndLon[1]?latAndLon[1]:0} )
          </div>
          <div className={styles.aMapInst} ref="container"></div>
          {
            this.state.btnDiv ? <div className={styles.mapBtn}>
              <Button
                onClick={()=>{
                  this.handleCancel();
                  THIS.state.cancal();
                }}>取消</Button>&nbsp;&nbsp;&nbsp;
              <Button
                type="primary"
                onClick={()=>{
                  //console.log(this)
                  this.handleCancel();
                  THIS.state.cancal();
                  THIS.state.cbk();
                }}>确定</Button>
            </div> : ''
          }

        </Modal>
      </div>
    )
  }

  //准备：即将被重新渲染，状态未变化
  componentWillUpdate(nextProps, nextState) {}

  //完成：正在被重新渲染，状态已变化
  componentDidUpdate(prevProps, prevState) {
  }

  // 已加载组件，收到新属性时调用
  componentWillReceiveProps(nextProps) {
    //console.log('nextProps: ',nextProps)

    if(nextProps.visible){
      let arr = nextProps.latAndLon.length <= 0 || !nextProps.latAndLon[0]? [] : nextProps.latAndLon;
        this.setState({visible: nextProps.visible,latAndLon:arr, btnDiv: nextProps.btnDiv,options:nextProps.options},()=>{
          this.loadAssetsAndMap(config.mapCfg.webServkey)
        });
    }
  }

  // 插入真实 DOM
  componentDidMount() {
    let THIS = this;
    // 加载Web服务地图实例
   // THIS.loadAssetsAndMap(config.mapCfg.webServkey)
  }


}


